package com.maltys.dp.sequence;

/**
 * @author maltys
 * @link <a href="https://leetcode.com/problems/palindromic-substrings/">回文子串</a>
 */
public class PalindromicSubstrings {
    public static void main(String[] args) {
        PalindromicSubstrings palindromicSubstrings = new PalindromicSubstrings();
        int count = palindromicSubstrings.countSubstrings("abcba");
        System.out.println(count);
    }

    public int countSubstrings(String s) {
        boolean[][] dp = new boolean[s.length() + 1][s.length() + 1];
        int res = 0;
        for (int i = s.length(); i > 0; i--) {
            for (int j = i; j <= s.length(); j++) {
                if (s.charAt(i - 1) == s.charAt(j - 1)) {
                    boolean isPalindromic = j - i <= 1 || dp[i + 1][j - 1];
                    if (isPalindromic) {
                        dp[i][j] = true;
                        res++;
                    }
                }
            }
        }
        return res;
    }

    public int countSubsequence(String s) {
        int[][] dp = new int[s.length() + 1][s.length() + 1];
        for (int i = 0; i <= s.length(); i++) {
            dp[i][i] = 1;
        }
        for (int i = s.length(); i > 0; i--) {
            for (int j = i + 1; j <= s.length(); j++) {
                dp[i][j] = dp[i + 1][j] + dp[i][j - 1];
                if (s.charAt(i - 1) == s.charAt(j - 1)) {
                    dp[i][j] -= dp[i + 1][j - 1];
                }
            }
        }
        return 1;
    }
}
